package com.dgut.springsecurity.handler;

import com.dgut.springsecurity.Details.UserAccountDetail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class UserLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    private static final Logger log = LoggerFactory.getLogger(UserLoginSuccessHandler.class);

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {


        // 会帮我们跳转到上一次请求的页面上
        //super.onAuthenticationSuccess(request, response, authentication);

        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        System.out.println(SecurityContextHolder.getContext().getAuthentication());
        UserAccountDetail userAccountDetail=(UserAccountDetail) authentication.getPrincipal();
        request.setAttribute("username",userAccountDetail.getUsername());
        String sessionId = request.getSession().getId();
        System.out.println(sessionId);
        //response.sendRedirect("/user?username="+userAccountDetail.getUsername());
        PrintWriter writer = response.getWriter();
        writer.write(sessionId);
        writer.flush();
        writer.close();
        //System.out.println("csdv");
    }


}
